// Copyright (c) 2018-2023 Coinbase, Inc. <https://www.coinbase.com/>

const fs = require('fs');
const glob = require('glob');
const sass = require('sass');
const path = require('path');

async function main() {
  // ================================
  // Compiling SCSS
  // ================================
  const scssFiles = glob.sync(`${__dirname}/src/**/*.scss`);
  for (const filePath of scssFiles) {
    console.info(`\nCompiling SCSS\n${filePath}...`);
    const css = sass.renderSync({ file: filePath, outputStyle: 'compressed' }).css.toString('utf8');
    const ts = `export default (() => \`${css}\`)();`;
    fs.writeFileSync(filePath.replace(/\.scss$/, '-css.ts'), ts, {
      mode: 0o644,
    });
  }

  // ================================
  // Compiling Telemetry Script
  // ================================
  const telemetrySource = path.join(__dirname, 'src/vendor-js/CCA/ca.js');
  const telemetryOutputTs = path.join(__dirname, 'src/core/telemetry/telemetry-content.ts');
  if (fs.existsSync(telemetrySource)) {
    console.info('\nGenerating Stringified Telemetry Script...');
    const telemetryContent = fs.readFileSync(telemetrySource, 'utf8');

    // Escape backticks and backslashes for template literal
    const escapedContent = telemetryContent
      .replace(/\\/g, '\\\\') // Escape backslashes
      .replace(/`/g, '\\`') // Escape backticks
      .replace(/\$\{/g, '\\${'); // Escape template literal expressions

    // Generate TypeScript file with stringified content
    const tsContent = `// This file is auto-generated by compile-assets.cjs
// Do not edit manually - changes will be overwritten

export const TELEMETRY_SCRIPT_CONTENT = \`${escapedContent}\`;
`;

    fs.writeFileSync(telemetryOutputTs, tsContent, { mode: 0o644 });
    console.info(`\nGenerated Stringified Telemetry Script: ${telemetryOutputTs}`);
  }

  console.info('\nAsset compilation complete!');
}

main();
